#!/bin/sh

# Download doujinshis from nhentai.net
# This script is Copylefted under the terms of the GNU GPL v2
# https://www.gnu.org/licenses/copyleft
# https://www.gnu.org/licenses/old-licenses/gpl-2.0.html

err() { 
	echo "Usage:
	nhentai -i ID -[OPTIONS] 
Options:
	-v: verbose cURL output;
	-i: specify the gallery's ID;
	-p: specify the number of pages you want to download. (default is all pages);
	-n: specify the name of the directory the doujinshi will be downloaded to. (default is the doujinshi's name);
	-f: force the download by deleting the already existing doujinshi directory. (if you specified a different name with -n previously, make sure to specify it again);
	-h: give you wisdom on how this beautiful piece of software works;	
	"
}

if [ -z $1 ]; then
 err
 exit 0
fi

if [ -z $(command -v python) ]; then
 echo "Python 3 is not installed in this system, please install it."
 exit 1
fi

curlArgs="-s -O -J --fail"
n=0

while getopts "i:p:n: h v f" opt
do
	case $opt in
		h) 
		  err && exit 1
		  ;; 
		i)
		  id=${OPTARG}
		  media_id=$(curl -s "https://nhentai.net/api/gallery/$id" |\
		  	python3 -c "import sys, json; print(json.load(sys.stdin)['media_id'])")
		  num_pages=$(curl -s "https://nhentai.net/api/gallery/$id" |\
		  	python3 -c "import sys, json; print(json.load(sys.stdin)['num_pages'])")
		  title_pretty=$(curl -s "https://nhentai.net/api/gallery/$id" |\
		  	python3 -c "import sys, json; print(json.load(sys.stdin)['title']['pretty'])")
		  ;;
		p) 
		  num_pages=${OPTARG}
		  ;;
		n)
		 title_pretty=${OPTARG}
		  ;;
		v)
		  curlArgs="-O -J --fail"
		  echo "cURL will output 404 errors. This is normal, don't worry."
		  ;;
		f)
		  rm -rf "$title_pretty"
		  ;;
	esac
done

if [ -d "$title_pretty" ]; then
 	echo "Directory exists, exiting."
 	exit 1
else
 	mkdir "$title_pretty"
	echo "Entering "$title_pretty""
	cd "$title_pretty"
fi
  	
	while [ $n != $num_pages ]
do
	page=$(( $n+1 ))
	n=$page
	echo "Downloading page $n out of $num_pages..."
	curl $curlArgs https://i.nhentai.net/galleries/$media_id/$page.jpg
	curl $curlArgs https://i.nhentai.net/galleries/$media_id/$page.png
done

echo "Done! $page pages downloaded, enjoy your fap!"
